package com.ruoyi.api;


import com.ruoyi.common.constant.ApiConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.dto.AppController;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.interceptor.annotation.IgnoreAuth;

import com.ruoyi.project.hidden.hiddenOrder.domain.HiddenOrder;
import com.ruoyi.project.hidden.hiddenOrder.service.IHiddenOrderService;
import com.ruoyi.project.web.carouselInfo.domain.CarouselInfo;
import com.ruoyi.project.web.carouselInfo.service.ICarouselInfoService;
import com.ruoyi.project.web.quesInfo.service.impl.QuesInfoServiceImpl;
import com.ruoyi.project.web.safeRule.domain.SafeRule;
import com.ruoyi.project.web.safeRule.service.ISafeRuleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;


/*通用数据接口*/
@RestController
@RequestMapping(value = "/api/data")
public class DataController extends AppController {

    private static final Logger log = LoggerFactory.getLogger(DataController.class);
    @Autowired
    private ICarouselInfoService carouselInfoService;
    @Autowired
    private ISafeRuleService safeRuleService;
    @Autowired
    private IHiddenOrderService orderService;




    /*首页轮播*/
    @RequestMapping(value = "/selectCarouselList")
    @IgnoreAuth
    public Object selectCarouselList() {
        CarouselInfo carouselInfo = new CarouselInfo();
        carouselInfo.setStatus("0");
        List<CarouselInfo> list = carouselInfoService.selectCarouselInfoList(carouselInfo);
        return writeResultRep(list);
    }

    /*安全细则*/
    @RequestMapping(value = "/selectSafeRuleList")
    @IgnoreAuth
    public Object selectSafeRuleList() {
        SafeRule safeRule = new SafeRule();
        safeRule.setStatus("0");
        List<SafeRule> list = safeRuleService.selectSafeRuleList(safeRule);
        return writeResultRep(list);
    }

    /*公告*/
    @RequestMapping(value = "/queryNoticeList")
    @IgnoreAuth
    public Object queryNoticeList() {
        HiddenOrder order = new HiddenOrder();
        order.setStatus(ApiConstants.DAI_FEN_PEI);
        List<HiddenOrder> list = orderService.selectHiddenOrderList(order);
        return writeResultRep(list);
    }

    /*单一文件上传*/
    @PostMapping("/uploadOneFile")
    @IgnoreAuth
    public Object uploadOneFile(MultipartFile file) {
        if (file == null) {
            return toResponsFail("缺少文件");
        }
        try {
            // 上传文件路径
            String photoPath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String photoSaveName = FileUploadUtils.upload(photoPath, file);
            /*生成缩略图*/
            return writeResultRep(photoSaveName);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return toResponsFail("系统错误");
        }
    }

    /*多文件上传*/
    @PostMapping("/uploadManyFiles")
    @IgnoreAuth
    public Object uploadManyFiles(MultipartFile[] files) {
        if (files.length == 0) {
            return toResponsFail("缺少文件");
        }
        StringBuffer manyUrls = new StringBuffer();
        try {
            // 上传文件路径
            String photoPath = RuoYiConfig.getUploadPath();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String photoSaveName = FileUploadUtils.upload(photoPath, file);
                if (StringUtils.isEmpty(manyUrls.toString())) {
                    manyUrls.append(photoSaveName);
                } else {
                    manyUrls.append("|" + photoSaveName);
                }
            }
            return writeResultRep(manyUrls.toString());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return toResponsFail("系统错误");
        }
    }


    /*视频文件上传*/
    @PostMapping("/uploadOneVideo")
    @IgnoreAuth
    public Object uploadOneVideo(MultipartFile file) {
        if (file == null) {
            return toResponsFail("缺少文件");
        }
        try {
            System.out.println("上传视频中..............");
            // 上传文件路径
            String videoPath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String videoSaveName = FileUploadUtils.upload(videoPath, file);
            System.out.println("成功上传视频返回的链接地址" + videoSaveName);
            return writeResultRep(videoSaveName);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return toResponsFail("系统错误");
        }
    }

    /*===========================================断点续传===================================================*/
    /**
     * 获取已上传的文件大小
     *
     * @param
     * @param
     */
    @RequestMapping("getChunkedFileSize")
    @IgnoreAuth
    public Object getChunkedFileSize(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return toResponsFail("缺少文件名称");
        }
        //存储文件的路径，根据自己实际确定
        String currentFilePath = RuoYiConfig.getUploadPath() + "/video/" + fileName;
        System.out.println("文件地址:" + currentFilePath);

        try {
            File source = new File(currentFilePath);
            if (source.exists()) {
                return source.length();
            } else {
                return 0L;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage(), e);
            return toResponsFail("系统错误");
        }
    }

    /**
     * 断点文件上传
     */
    @RequestMapping("breakPointUploadFileDo")
    @IgnoreAuth
    public Object breakPointUploadFileDo(MultipartFile file, long startLength, String fileName) {

        if (file.getSize() <= 0) {
            return toResponsFail("请选择上传的文件！");
        }
        System.out.println("从" + startLength + "开始续传");

        String writeFileName = RuoYiConfig.getUploadPath() + "/video/" + fileName;
        File source = new File(writeFileName);
        RandomAccessFile writeFile=null;
        InputStream iStream=null;
        // 存在文件
        try {
            if (source.exists()) {

                writeFile = new RandomAccessFile(source, "rw");
            } else {

                // 不存在文件，根据文件标识创建文件
                writeFile = new RandomAccessFile(writeFileName, "rw");
            }
            writeFile.seek(startLength);
            byte[] arr = new byte[1024];
            int len = 0;
             iStream = file.getInputStream();
            while ((len = iStream.read(arr)) != -1) {
                writeFile.write(arr, 0, len);
            }

        } catch (final Exception e) {
            throw new RuntimeException("断点上传文件异常", e);
        } finally {
            try {
                iStream.close();
                writeFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return writeResultRep(writeFileName);
    }

    /*==================================================分片=========================================================*/

    /**
     * 上传分片文件
     * @param guid
     * @param chunk
     * @param file
     */
    @RequestMapping("/uploadBurstFile")
    @IgnoreAuth
    public Object uploadBurstFile(MultipartFile file, String guid, Integer chunk){
        if(file==null || StringUtils.isEmpty(guid) || StringUtils.isNull(chunk)){
            return toResponsFail("缺少参数传递");
        }
        try {
            String filePath= RuoYiConfig.getUploadPath() + "/video/";
            // 临时目录用来存放所有分片文件
            String tempFileDir = filePath + guid;
            File parentFileDir = new File(tempFileDir);
            if (!parentFileDir.exists()) {
                parentFileDir.mkdirs();
            }
            // 分片处理时，前台会多次调用上传接口，每次都会上传文件的一部分到后台
            File tempPartFile = new File(parentFileDir, guid + "_" + chunk + ".part");
            FileUtils.copyInputStreamToFile(file.getInputStream(), tempPartFile);
            return writeResultRep();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return toResponsFail("系统错误");
        }
    }

    /**
     * 合并分片文件
     * @param guid
     * @param fileName
     * @throws Exception
     */
    @RequestMapping( "/mergeBurstFile")
    @IgnoreAuth
    public Object mergeBurstFile(String guid,String fileName){
        // 得到 destTempFile 就是最终的文件
        try {
            String filePath= RuoYiConfig.getUploadPath() + "/video/";
            String nowDate= DateUtils.dateTimeNow();
            File parentFileDir = new File(filePath  +guid );
            if(parentFileDir.isDirectory()){
                File destTempFile = new File(filePath+nowDate, fileName);
                //先得到文件的上级目录，并创建上级目录，在创建文件,
                if (!destTempFile.getParentFile().exists()){
                    destTempFile.getParentFile().mkdir();
                }
                if(!destTempFile.exists()){
                    try {
                        //创建文件
                        destTempFile.createNewFile(); //上级目录没有创建，这里会报错
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(parentFileDir.listFiles().length);
                for (int i = 0; i < parentFileDir.listFiles().length-1; i++) {
                    File partFile = new File(parentFileDir, guid + "_" + i + ".part");
                    FileOutputStream destTempfos = new FileOutputStream(destTempFile, true);
                    //遍历"所有分片文件"到"最终文件"中
                    FileUtils.copyFile(partFile, destTempfos);
                    destTempfos.close();
                }
                // 删除临时目录中的分片文件
                FileUtils.deleteDirectory(parentFileDir);
                return writeResultRep(Constants.RESOURCE_PREFIX + "/upload/video/"+nowDate + "/" +fileName);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return toResponsFail("系统错误");
        }
        return null;
    }

}
